package com.zan.handler;

import com.alibaba.fastjson.JSON;
import com.zan.utils.WebUtils;
import com.zan.vo.ResponseResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Zan
 * @Date 2023/10/18 14:28
 * @Description : 自定义处理认证过程中的异常的类
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 401 - 未认证的授权码
        ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(), "用户认证失败，请重新登录");
        String jsonStr = JSON.toJSONString(result);
        // 处理认证过程中的异常
        WebUtils.renderString(response, jsonStr);
    }
}
